package com.cuit.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cuit.reggie.common.R;
import com.cuit.reggie.entity.User;
import com.cuit.reggie.service.UserService;
import com.cuit.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)){
            //生成随机四位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);
            //调用阿里云

            //验证码保存到session
            session.setAttribute(phone,code);

            return R.success("手机验证码发送成功");
        }

        return R.error("发送失败");
    }

    /**
     * 用户登录
     * @param
     * @return
     */
    @PostMapping("/login")
    public R<User> userLogin(@RequestBody Map ob,HttpSession session){
        log.info("手机号码：{}",ob.get("phone"));

        String phone = ob.get("phone").toString();

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getPhone,phone);

        User user = userService.getOne(lambdaQueryWrapper);

        //新用户
        if (user==null){
            user  = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }

        session.setAttribute("user",user.getId());
        return R.success(user);
    }
}
